package com.sh.common.context;

import cn.hutool.core.convert.Convert;
import com.sh.constant.SecurityConstants;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取当前线程变量中的 用户id、用户名称、Token等信息 
 * 注意： 必须在网关通过请求头的方法传入，同时在HeaderInterceptor拦截器设置值。 否则这里无法获取
 *
 */
public class AppContextHolder
{
    private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal<>();

    public static void set(String key, Object value) {
        Map<String, Object> map = getLocalMap();
        map.put(key, value == null ? StringUtils.EMPTY : value);
    }

    public static String get(String key) {
        Map<String, Object> map = getLocalMap();
        return Convert.toStr(map.getOrDefault(key, StringUtils.EMPTY));
    }


    public static Map<String, Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new ConcurrentHashMap<String, Object>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

    public static void setLocalMap(Map<String, Object> threadLocalMap)
    {
        THREAD_LOCAL.set(threadLocalMap);
    }

    public static String getUserId()
    {
        return Convert.toStr(get(SecurityConstants.DETAILS_USER_ID), "");
    }

    public static void setUserId(String account)
    {
        set(SecurityConstants.DETAILS_USER_ID, account);
    }

    public static void setUser(String userId,String userCode,String userName,Boolean isAdmin){
        setUserId(userId);
        setUserCode(userCode);
        setUserName(userName);
        setAdmin(isAdmin);
    }

    public static void setAdmin(Boolean isAdmin){
        set(SecurityConstants.ADMIN, isAdmin);
    }
    public static Boolean getAdmin(){
        return Boolean.valueOf(get(SecurityConstants.ADMIN));
    }
    public static void setUserCode(String userCode){
        set(SecurityConstants.DETAILS_USER_CODE, userCode);
    }
    public static String getUserCode(){
        return get(SecurityConstants.DETAILS_USER_CODE);
    }
    public static String getUserName()
    {
        return get(SecurityConstants.DETAILS_USER_NAME);
    }

    public static void setUserName(String username)
    {
        set(SecurityConstants.DETAILS_USER_NAME, username);
    }

    public static void remove()
    {
        THREAD_LOCAL.remove();
    }
}
